/* eslint  react/no-string-refs: 0 */
import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import { Input, Grid, Form, Select, Message, Icon, Balloon } from '@alifd/next';
import { observer, inject } from 'mobx-react';
import { ApiOfGatewayList, ApiOfResourceCreate, ApiOfResourceUpdate } from '#/utils/coreApiDefine'
import './EditForm.scss';

const { Row, Col } = Grid;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: { xxs: 6, s: 3, l: 4 },
  wrapperCol: { s: 12, l: 12 }
};

const configFieldLabel = (<span>
  扩展配置：<Balloon type="primary" trigger={<Icon type="help" size="small" />} closable={false}>
    <pre>
      {`Modbus设备配置
{"slave": 1}
slave: modbus设备必填项。

Bacnet设备配置
{
  "networkNumber": 0,
  "ipAddress": "10.1.5.125",
  "port": 47808,
  "instanceNumber": 301101
}

SNMP和OPC目前没有设备扩展属性
`}
    </pre>
  </Balloon>
</span>);

const codeFieldLabel = (<span>
  编号：<Balloon type="primary" trigger={<Icon type="help" size="small" />} closable={false}>
    非特殊情况，不用人工录入编号，后台会自动生成
    </Balloon>
</span>);
const associateFieldLabel = (<span>
  子系统标识：<Balloon type="primary" trigger={<Icon type="help" size="small" />} closable={false}>
    手动录入，用于对应子系统Trap告警。
    </Balloon>
</span>);

@inject('dictstore')
@observer
export default class SettingsForm extends Component {
  static displayName = 'EditForm';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.formData = this.props.formData ? { ...this.props.formData } : {};
    this.state = {
      value: {
        id: this.formData.id,
        name: this.formData.name,
        code: this.formData.code,
        type: this.formData.type,
        associate: this.formData.associate,
        gatewayCode: this.formData.gatewayCode,
        config: this.formData.config ? this.formData.config : '',
        comment: this.formData.comment,
        executionCycle: this.formData.executionCycle
      },
    };
  }

  componentDidMount() {
    ApiOfGatewayList().then(response => {
      const { data } = response;
      let gatewayKPs = data.map(function (item, key, ary) {
        return { value: item.code, label: item.name + '(' + item.physicalConnType + ')' };
      });
      this.setState({
        gateways: gatewayKPs,
      });
    }).catch(error => {
      console.log(error);
    })
  }

  formChange = (value) => {
    this.setState({
      value,
    });
  };

  validateAllFormField = (values, errors) => {
    let that = this;
    if (!errors) {
      if (!!values.config) {
        let isJSON = true;
        try {
          JSON.parse(values.config)
        } catch (e) {
          isJSON = false
        }
        if (!isJSON) {
          Message.error('扩展配置格式不正确！');
          return;
        }
      }
      let updated = values.id !== undefined;
      if (updated) {
        ApiOfResourceUpdate(this.formData.code, values).then(() => that.props.submitCallback('success'))
      } else {
        ApiOfResourceCreate(values).then(() => that.props.submitCallback('success'))
      }
    } else {
      // 处理表单报错
    }
  };

  render() {
    return (
      <div className="settings-form">
        <IceContainer>
          <Form
            value={this.state.value}
            onChange={this.formChange}
            ref="form"
          >
            <div style={styles.formContent}>
              <Input name="id" htmlType="hidden" />
              <FormItem size="medium" label="名称：" {...formItemLayout} required maxLength={30} requiredMessage="必填">
                <Input name="name" placeholder="设备名称" />
              </FormItem>
              <FormItem size="medium" label={codeFieldLabel} {...formItemLayout}>
                <Input name="code" placeholder="设备编号" disabled={false} />
              </FormItem>
              <FormItem size="medium" label="设备类型：" {...formItemLayout} required requiredMessage="必填">
                <Select name="type" dataSource={this.props.dictstore.ResourceTypeDS} hasClear={true} style={{ width: '100%' }} />
              </FormItem>
              <FormItem size="medium" label="采集周期：" {...formItemLayout} required requiredMessage="必填">
                <Input name="executionCycle" htmlType="number" placeholder="采集周期" />
              </FormItem>
              <FormItem size="medium" label="网关：" {...formItemLayout} >
                <Select name="gatewayCode" dataSource={this.state.gateways} hasClear={true} style={{ width: '100%' }} />
              </FormItem>
              <FormItem size="medium" label={configFieldLabel} {...formItemLayout} >
                <Input.TextArea name="config" placeholder="{... ...}" />
              </FormItem>
              <FormItem size="medium" label={associateFieldLabel} {...formItemLayout}>
                <Input name="associate" placeholder="子系统标识" />
              </FormItem>
              <FormItem size="medium" label="备注" {...formItemLayout}>
                <Input.TextArea name="comment"  placeholder="备注" />
              </FormItem>
              <Row style={{ marginTop: 20 }}>
                <Col offset="3">
                  <Form.Submit
                    size="medium"
                    type="primary"
                    style={{ width: 100 }}
                    validate
                    onClick={this.validateAllFormField}
                  >
                    保 存
              </Form.Submit>
                </Col>
              </Row>
            </div>
          </Form>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  label: {
    textAlign: 'right',
  },
  formContent: {
    width: '100%',
    position: 'relative',
  },
  formItem: {
    alignItems: 'center',
    marginBottom: 25,
  },
  formTitle: {
    margin: '0 0 20px',
    paddingBottom: '10px',
    borderBottom: '1px solid #eee',
  },
};
